package com.sayice.coursetable.logic.utils;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES-128-CBC 加密工具类
 */
public abstract class AesUtils {
    private static final String AES_CHARS = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
    public static final String AES_KEY = "rjBFAaHsNkKAhpoi";

    /**
     * 获取加密字符串
     */
    public static String encryptAES(String data, String aesKey) {
        return encrypt(randomString(64) + data, aesKey, randomString(16));
    }

    /**
     * 获取解密字符串
     */
    public static String decryptAES(String data, String aesKey) {
        return decrypt(data, aesKey, randomString(16)).substring(64);
    }

    /**
     * 加密
     */
    private static String encrypt(String data, String key0, String iv0) {
        byte[] encrypted = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] key = key0.getBytes();
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv0.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            encrypted = cipher.doFinal(data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    /**
     * 解密
     */
    private static String decrypt(String data, String key0, String iv0) {
        byte[] encrypted = Base64.decode(data, Base64.DEFAULT);
        byte[] decrypted = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] key = key0.getBytes();
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv0.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            decrypted = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    /**
     * 生成随机字符串
     *
     * @param len 字符串长度
     */
    private static String randomString(int len) {
        StringBuilder retStr = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int index = (int) Math.floor(Math.random() * AES_CHARS.length());
            retStr.append(AES_CHARS.charAt(index));
        }
        return retStr.toString();
    }
}
